import { REMOVE_TAB, SET_ACTIVE_TAB_PATHNAME, SET_KEEP_ALIVE_TABS } from '@/actions/tabs/types.js';
import { defaultRoute } from '@/router/index.jsx';

const stateInit = {
  keepAliveTabs: [],
  activeTabPathname: undefined
};

function tabsReducer(state = stateInit, action) {
  if (action.type === SET_KEEP_ALIVE_TABS) {
    const findIndex = state.keepAliveTabs.findIndex(
      (item) => item.pathname === defaultRoute.pathname
    );
    if (findIndex === -1) {
      const findIndex = action.payload?.findIndex(
        (item) => item.pathname === defaultRoute.pathname
      );
      if (findIndex === -1) {
        return {
          ...state,
          keepAliveTabs: action.payload ? [defaultRoute, ...action.payload] : [defaultRoute]
        };
      }
    }
    return {
      ...state,
      keepAliveTabs: action.payload ?? []
    };
  }
  if (action.type === SET_ACTIVE_TAB_PATHNAME) {
    return {
      ...state,
      activeTabPathname: action.payload
    };
  }
  if (action.type === REMOVE_TAB) {
    const keepAliveTabs = [...state.keepAliveTabs];
    keepAliveTabs.splice(action.payload, 1);
    return {
      ...state,
      keepAliveTabs: keepAliveTabs
    };
  }
  return state;
}

export default tabsReducer;
